package com.ruoyi.combat.service.userlocation.impl;

import java.util.*;

import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.userlocation.*;
import com.ruoyi.combat.mapper.userlocation.CombatLocationTaskMapper;
import com.ruoyi.combat.mapper.userlocation.ConfuseTextMapper;
import com.ruoyi.combat.mapper.userlocation.ConfuseUserMapper;
import com.ruoyi.combat.service.socialmedia.CombatCrawlService;
import com.ruoyi.combat.service.userlocation.*;
import com.ruoyi.combat.util.CityUtil;
import com.ruoyi.combat.util.CoordinateUtils;
import com.ruoyi.combat.util.MethodUseUtils;
import com.ruoyi.combat.util.UserLocationTask;
import com.ruoyi.combat.util.weibo.WeiboApiUtil;
import com.ruoyi.combat.util.weibo.WeiboUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.file.service.ISysFileService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 抗定位任务Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-30
 */
@Service
public class CombatLocationTaskServiceImpl implements ICombatLocationTaskService {
    @Autowired
    private CombatLocationTaskMapper combatLocationTaskMapper;

    @Autowired
    private ConfuseTextMapper confuseTextMapper;

    @Autowired
    private ICombatWarnService combatWarnService;

    @Autowired
    private ISysFileService fileService;
    @Autowired
    private ICombatBlogService combatBlogService;
    @Autowired
    private MethodUseUtils methodUseUtils;

    @Autowired
    private ICombatRelationService combatRelationService;
    @Autowired
    private ICombatUserService combatUserService;

    @Autowired
    private ConfuseUserMapper confuseUserMapper;
    @Autowired
    private CombatCrawlService combatCrawlService;
    @Autowired
    private WeiboApiUtil weiboApiUtil;
    @Autowired
    private WeiboUtil weiboUtil;



    /**
     * 查询抗定位任务
     *
     * @param id 抗定位任务主键
     * @return 抗定位任务
     */
    @Override
    public CombatLocationTask selectCombatLocationTaskById(Long id) {
        return combatLocationTaskMapper.selectCombatLocationTaskById(id);
    }

    /**
     * 查询抗定位任务列表
     *
     * @param combatLocationTask 抗定位任务
     * @return 抗定位任务
     */
    @Override
    public List<CombatLocationTask> selectCombatLocationTaskList(CombatLocationTask combatLocationTask) {
        List<CombatLocationTask> combatLocationTasks = combatLocationTaskMapper.selectCombatLocationTaskList(combatLocationTask);
        for (CombatLocationTask task : combatLocationTasks){
            CombatUser combatUser = combatUserService.selectCombatUserByUserId(task.getUserId());
            if(combatUser!=null){
                task.setUseredId(combatUser.getId());
            }
        }
        return combatLocationTasks;
    }

    /**
     * 新增抗定位任务
     *
     * @param combatLocationTask 抗定位任务
     * @return 结果
     */
    @Override
    public int insertCombatLocationTask(CombatLocationTask combatLocationTask) {
        if (StringUtils.isNotEmpty(combatLocationTask.getTargetLocation())) {
            String method = combatLocationTask.getMethod();
            Long warnid = combatLocationTask.getWarnid();

            CombatWarn combatWarn = combatWarnService.selectCombatWarnById(warnid);
            String userid = combatWarn.getUserid();
            combatLocationTask.setUserId(userid);
            combatLocationTask.setStartime(new Date());
            String city = combatLocationTask.getTargetLocation();
            if (StringUtils.isEmpty(city)) {
                throw new RuntimeException("请选择定位城市");
            }
            if ("社交内容混淆".equals(method)) {

                ConfuseText confuseText1 = new ConfuseText(city);
                confuseText1.setStatus("0");
                List<ConfuseText> texts = confuseTextMapper.selectConfuseTextList(confuseText1);
                if (texts != null & texts.size() > 0) {
                    Random random = new Random();
                    int r = random.nextInt(texts.size());
                    String confuseContent = texts.get(r).getConfuseContent();
                    List<String> list = new ArrayList<>();
                    list.add(confuseContent);
                    Map<String, Object> stringObjectMap = methodUseUtils.methodUseLogs(15l, JSONUtil.toJsonStr(list));
                    Map coordinate = (Map) stringObjectMap.get("coordinate");//获取坐标；
                    double lat = Double.parseDouble(String.valueOf(coordinate.get("lat")));
                    double lng = Double.parseDouble(String.valueOf(coordinate.get("lng")));
                    combatLocationTask.setConfuseText(texts.get(r).getConfuseContent());
                    combatLocationTask.setConfuseImgs(texts.get(r).getConfuseImgs());
                    combatLocationTask.setResultLat(String.valueOf(lat));
                    combatLocationTask.setResultLon(String.valueOf(lng));
                    combatLocationTask.setEndtime(new Date());
                    combatLocationTask.setState("已完成");
                    /*String confuseImgs = texts.get(0).getConfuseImgs();
                    byte[] bytes = fileService.download(confuseImgs);*/
                    CombatUser combatUser = combatUserService.selectCombatUserByUserId(userid);
                    String token = combatUser.getToken();
                    ConfuseText confuseText = texts.get(r);
                    String confuseImgs = confuseText.getConfuseImgs();
                    String pic_id = "";
                    List<Map> fileList = new ArrayList<>();
                    if(StringUtils.isNotEmpty(confuseImgs)) {
                        String[] split = confuseImgs.split(",");
                        List<Map> imgList = new ArrayList<>();
                        for (int i = 0; i < split.length; i++) {
                            String s = split[i];
                            byte[] download = fileService.download(s);
                            String s1 = s.split("\\.")[1];
                            s1 = i+"."+s1;
                            Map map = new HashMap<>();
                            map.put("fileData", download);
                            map.put("filename", s1);
                        }
//                        for (String s : split) {
//                            String[] split1 = s.split("\\.");
//                            String imgType = split1[split1.length-1];
//                            byte[] download = fileService.download(s);
//
////                            String s1 = weiboApiUtil.uploadImg(token, download,imgType);
////                            Map bean = JSONUtil.toBean(s1, Map.class);
////                            String pid = String.valueOf(bean.get("pid"));
////                            if (StringUtils.isNotEmpty(pid)) {
////                                Map<String,String> data = new HashMap();
////                                String type = "image/"+imgType;
////                                data.put("type",type);
////                                data.put("pid",pid);
////                                imgList.add(data);
////                            }
//                        }
                        pic_id = JSONUtil.toJsonStr(imgList);
                    }

//                    String s = weiboApiUtil.sendContent(token, texts.get(r).getConfuseContent(), pic_id, IpUtils.getIpAddr());
                    String s = weiboUtil.send_weibo(userid, texts.get(r).getConfuseContent(), fileList);

                    combatCrawlService.crawlWeiboByUserId(String.valueOf(combatUser.getId()));
                }
            } else if ("社交关系混淆".equals(method)) {
                //获取用户社交关系
                String data = checkUserRelation(userid,city);
                //抗用户社交关系定位
                Map<String, Object> stringObjectMap = methodUseUtils.methodUseLogs(19l, data);
                if (stringObjectMap != null) {
                    //新的社交关系定位
                    String jsonStr = JSONUtil.toJsonStr(stringObjectMap.get("fake_relation"));
                    Map<String, Object> re = methodUseUtils.methodUseLogs(17L, jsonStr);
                    if (re.get("results") != null) {
                        String results = JSONUtil.toJsonStr(re.get("results"));
                        List<Map> list1 = JSONUtil.toList(results, Map.class);
                        if (list1.size() > 0) {
                            try {
                                Map<String, String> address = getAddress(list1.get(0));
                                combatLocationTask.setResultLat(address.get("lat"));
                                combatLocationTask.setResultLon(address.get("lng"));
                                combatLocationTask.setEndtime(new Date());
                                combatLocationTask.setState("已完成");
                            } catch (Exception e) {
                                combatLocationTask.setResultLat("25.037798");
                                combatLocationTask.setResultLon("121.565170");
                                combatLocationTask.setEndtime(new Date());
                                combatLocationTask.setState("已完成");
                            }
                        }
                    }
                    //分析混淆后的社交关系
                    Map bean = JSONUtil.toBean(jsonStr, Map.class);
                    List<Map> list = JSONUtil.toList(JSONUtil.toJsonStr(bean.get("data")), Map.class);
                    List<CombatRelation> relationList = new ArrayList<>();
                    for (Map map : list) {
                        List<CombatRelation> combatRelations = checkUserRelation(map);
                        relationList.addAll(combatRelations);
                    }
                    List<Map> listt1 = new ArrayList<>();
                    List<String> targetidList = new ArrayList<>();
                    for (CombatRelation relation : relationList) {
                        String targetid = relation.getTargetid();
                        String targetName = relation.getTargetName();
                        Map map = new HashMap<>();
                        map.put("id", targetid);
                        map.put("name", targetName);
                        listt1.add(map);
                        targetidList.add(targetid);
                    }
                    CombatUser combatUser = combatUserService.selectCombatUserByUserId(userid);
                    String token = combatUser.getToken();
                    int size = targetidList.size();
                    if(size>5){
                        targetidList = targetidList.subList(0,5);
                    }

                    //新增关注
                    weiboApiUtil.tofollow(userid, targetidList);
                    combatCrawlService.crawlWeiboByUserId(String.valueOf(combatUser.getId()));

                    String jsonStr1 = JSONUtil.toJsonStr(listt1);
                    combatLocationTask.setRelationContent(jsonStr1);
                    combatWarn.setWarnState("1");
                    combatWarnService.updateCombatWarn(combatWarn);

                    new Thread(new UserLocationTask(combatUser, combatUserService, combatRelationService, methodUseUtils));
                }
            }
        }
        return combatLocationTaskMapper.insertCombatLocationTask(combatLocationTask);
    }

    public Map<String, String> getAddress(Map coordinate) {
        Map<String, String> re = new HashMap<>();
        String locationPos = String.valueOf(coordinate.get("predicted_city"));
        double lat = Double.parseDouble(String.valueOf(coordinate.get("lat")));
        double lng = Double.parseDouble(String.valueOf(coordinate.get("lng")));
        re.put("city", locationPos);
        re.put("lat", String.valueOf(lat));
        re.put("lng", String.valueOf(lng));
        return re;
    }

    public List<CombatRelation> checkUserRelation(Map map) {
        List<CombatRelation> list = new ArrayList<>();
        String fromCity = String.valueOf(map.get("fromCity"));
        String fromId = String.valueOf(map.get("fromId"));
        String fromName = String.valueOf(map.get("fromName"));
        String relation = String.valueOf(map.get("relation"));
        String toCity = String.valueOf(map.get("toCity"));
        String toId = String.valueOf(map.get("toId"));
        String toName = String.valueOf(map.get("toName"));
        CombatRelation combatRelation = new CombatRelation();
        combatRelation.setUserid(fromId);
        combatRelation.setTargetid(toId);
        List<CombatRelation> combatRelations = combatRelationService.selectCombatRelationList(combatRelation);
        if (combatRelations.size() == 0) {
            combatRelation.setUsername(fromName);
            combatRelation.setUserCity(fromCity);
            combatRelation.setTargetName(toName);
            combatRelation.setTargetCity(toCity);
            combatRelation.setRelation("关注");
            combatRelation.setStatus("1");
//            combatRelationService.insertCombatRelation(combatRelation);
            list.add(combatRelation);
        }
        return list;
    }

    /**
     * 获取用户社交关系
     * @param userId
     * @return
     */
    public String checkUserRelation(String userId,String city) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Map> userMap = new HashMap<>();
        new CombatUser();
        CombatUser user = combatUserService.selectCombatUserByUserId(userId);
        Map<String, String> data1 = new HashMap();
        data1.put("name", user.getUserNickname());
        data1.put("city", user.getUserHomeAddr());
        userMap.put(user.getUserId(), data1);


        CombatRelation combatRelation = new CombatRelation();
        combatRelation.setUserid(userId);
        List<CombatRelation> combatRelations = combatRelationService.selectCombatRelationList(combatRelation);
//        combatRelation.setUserid(null);
//        combatRelation.setTargetid(userId);
//        List<CombatRelation> combatRelations1 = combatRelationService.selectCombatRelationList(combatRelation);
//        combatRelations.addAll(combatRelations1);

        List<Map<String, String>> list = new ArrayList<>();
        List<Map<String, String>> fake_user = new ArrayList<>();
        for (CombatRelation relation : combatRelations) {
            Map<String, String> data = new HashMap<>();
            String userid = relation.getUserid();
            String username = relation.getUsername();
            String userCity = relation.getUserCity();
            String targetid = relation.getTargetid();
            String targetName = relation.getTargetName();
            String targetCity = relation.getTargetCity();
            data.put("toId", targetid);
            data.put("toName", targetName);
            data.put("toCity", targetCity);
            data.put("fromId", userid);
            data.put("fromName", user.getUserNickname());
            data.put("fromCity", user.getUserHomeAddr());
            data.put("relation", "关注");
            list.add(data);

        }
        CombatUser user2 = new CombatUser();
        user2.setUserId(userId);
        user2.setCity(city);

        List<CombatUser> combatUserList = combatUserService.selectCombatUserByCity(user2);
        for (CombatUser user1 : combatUserList){
            Map<String, String> data2 = new HashMap<>();
            data2.put("userid", user1.getUserId());
            data2.put("name", user1.getUserName());
            data2.put("city", city);
            fake_user.add(data2);
        }

        if(fake_user.size()==0) {
            ConfuseUser confuseUser = new ConfuseUser();
            List<ConfuseUser> confuseUsers = confuseUserMapper.selectConfuseUserList(confuseUser);

            for (ConfuseUser user1 : confuseUsers) {
                Map<String, String> data2 = new HashMap<>();
                data2.put("userid", user1.getUserId());
                data2.put("name", user1.getUserName());
                data2.put("city", user1.getCity());
                fake_user.add(data2);
            }
        }



        int size1 = list.size();
        if (size1 > 20){
            list = list.subList(0, 20);
        }

        result.put("target_userid", userId);
        result.put("data", list);
        result.put("fake_user", fake_user);
        String jsonStr = JSONUtil.toJsonStr(result);
//        Map<String, Object> stringObjectMap = methodUseUtils.methodUseLogs(19L, jsonStr);
//        //
//        String code = String.valueOf(stringObjectMap.get("data"));
//        if("200".equals(code)){
//            String results = JSONUtil.toJsonStr(stringObjectMap.get("results"));
//            List<Map> list1 = JSONUtil.toList(results, Map.class);
//            if(list1.size()>0) {
////                checkAddress(userId, list1.get(0));
//            }
//
//        }
        return jsonStr;
    }

    /**
     * 修改抗定位任务
     *
     * @param combatLocationTask 抗定位任务
     * @return 结果
     */
    @Override
    public int updateCombatLocationTask(CombatLocationTask combatLocationTask) {
        return combatLocationTaskMapper.updateCombatLocationTask(combatLocationTask);
    }

    /**
     * 批量删除抗定位任务
     *
     * @param ids 需要删除的抗定位任务主键
     * @return 结果
     */
    @Override
    public int deleteCombatLocationTaskByIds(Long[] ids) {
        return combatLocationTaskMapper.deleteCombatLocationTaskByIds(ids);
    }

    /**
     * 删除抗定位任务信息
     *
     * @param id 抗定位任务主键
     * @return 结果
     */
    @Override
    public int deleteCombatLocationTaskById(Long id) {
        return combatLocationTaskMapper.deleteCombatLocationTaskById(id);
    }

    public void updateweibo(CombatLocationTask combatLocationTask) {
        combatLocationTaskMapper.updateCombatLocationTask(combatLocationTask);
    }
}
